var utils = require("../Utils/utils")
var model = require("../DAO/model")
var md5 = require("md5")

//var md5 = require("blueimp-md5")
var session = require('express-session')

//根据email获取用户信息
module.exports.getUserByEmail = function(email, callback) {
	model.User.findOne({
		email: email
	}, function(err, doc) {
		if(err) {
			callback(err)
			return
		}
		callback(null, doc)
	})
}

//保存一个用户
module.exports.saveOneUser = function(user, callback) {
	model.User.find({
		email: user.email
	}, function(err, docs) {
		if(err) {
			callback(err)
			return
		}
		model.User.find({}, function(err, docs) {
			if(err) {
				callback(err)
				return
			}
			user.id = docs.length + 1
			console.log(`注册成功！用户id为${user.id}`)
			console.log(user)
			var new_user = model.User(user)
			new_user.save(function(err) {

				if(err) {
					callback(err)
					return
				}
				callback(null)
			})
		})

	})
}

//注册接口
module.exports.register = function(req, res) {

	model.User.find({
		email: req.body.email
	}, function(err, docs) {
		if(!err) {
			if(docs.length == 0) {
				req.body.createTime = utils.getTime();
				model.User.find({}, function(err, docs) {
					if(!err) {
						req.body.id = docs.length + 1

						req.body.password = md5(md5(req.body.password))
						var user = model.User(req.body)
						user.save(function(err) {
							if(!err) {
								res.send({
									info: "注册成功！"
								})
							}
						})
					} else {
						console.log("数据库查询失败！")
					}
				})
			} else {
				console.log("用户已存在")
				res.send({
					info: "用户已存在"
				})
			}
		} else {
			console.log("数据库查询失败！")
		}
	})

}

//获取登陆页面
module.exports.getLoginPage = function(req, res) {
	res.render("login.html", {
		title: "login",
		loc: "login"
	})
}

//登陆接口
module.exports.login = function(req, res) {
	req.body.password = md5(md5(req.body.password))
	model.User.find({
		email: req.body.email,
		password: req.body.password
	}, function(err, docs) {

		if(docs.length == 1) {
			req.session.userInfo = {
				email: req.body.email,
				isLogin: true,
				user_id: docs[0].id
			}
			//req.session.isLogin = true
			res.send({
				info: "登陆 成功"
			})

		} else if(docs.length == 0) {
			res.send({
				info: "邮箱或密码错误！"
			})
			console.log("密码错误")
		} else {
			res.send({
				info: "服务器内部错误！"
			})
		}

	})
}

//获取标签页面
module.exports.getTagPage = function(req, res) {
	res.render("tag-list.html", {
		title: "tag",
		loc: "tag"
	})
}

module.exports.getConfigPage = function(req, res) {
	console.log(req.session.userInfo.avatar)
	res.render("userConfig.html", {
		isLogin: req.session.userInfo.isLogin,
		name: req.session.userInfo.name,
		avatar: req.session.userInfo.avatar
	})
}

module.exports.getLogoutPage = function(req, res) {
	req.session.userInfo = null;
	res.render("register_login.html", {
		title: "register",
		loc: "register"
	})
}